import storage from '@/utils/storage'
import * as LoginApi from '@/api/login.js'


const user = {
  state: {
    // 用户认证token
    token: '',
    // 用户信息
    userInfo: {},
	isLogin:false
  },

  mutations: {
    SET_TOKEN: (state, value) => {
      state.token = value
    },
    SET_USER_INFO: (state, value) => {
      state.userInfo = value
    },
	SET_ISLOGIN:(state, value) => {
      state.isLogin = value
    },
  },

  actions: {

    // 用户登录(普通登录: 输入手机号和验证码)
    Login({ commit }, data) {
      return new Promise((resolve, reject) => {
        LoginApi.login(data)
          .then(response => {
            // 过期时间30天
            const expiryTime = 30 * 86400
            // 保存tokne和userId到缓存
            storage.set('ACCESS_TOKEN', response.token, expiryTime)
			storage.set('isLogin',true)
            // 记录到store全局变量
            commit('SET_TOKEN', response.token)
			commit('SET_ISLOGIN', true)
            resolve(response)
          })
          .catch(reject)
      })
    },
	
	//获取用户基本信息
	GetInfo({ commit }, data) {
		return new Promise((resolve, reject) => {
		  LoginApi.getInfo(data)
		    .then(response => {
				const result = response 
				const expiryTime = 30 * 86400
				storage.set('userInfo', response, expiryTime)
				commit('SET_USER_INFO', response)
				resolve(response)
		    })
		    .catch(reject)
		})
	},

    // 退出登录
    LogOut({ commit }, data) {
      const _this = this
      return new Promise((resolve, reject) => {
        if (_this.getters.token) {
          // 删除缓存中的tokne和userId
          storage.remove('userInfo')
          storage.remove('AccessToken')
		  storage.remove('isLogin')
		  
          // 记录到store全局变量
          commit('SET_TOKEN', '')
          commit('SET_USER_INFO', null)
		  commit('SET_ISLOGIN', false)
          resolve()
        }
      })
    }

  }
}

export default user
